package com.light.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.light.common.pojo.ESPojo;
import com.light.gulimall.search.config.ESConfig;
import com.light.gulimall.search.constant.ESConstants;
import com.light.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public boolean productStatusUp(List<ESPojo> esPojos) throws IOException {

        boolean flag = false;

        BulkRequest bulkRequest = new BulkRequest();
        for (ESPojo esPojo : esPojos) {
            IndexRequest indexRequest = new IndexRequest(ESConstants.PRODUCT_INDEX);
            indexRequest.id(esPojo.getSkuId().toString());
            String esPojoStr = JSON.toJSONString(esPojo);
            IndexRequest request = indexRequest.source(esPojoStr, XContentType.JSON);
            bulkRequest.add(request);
        }

        BulkResponse response = restHighLevelClient.bulk(bulkRequest, ESConfig.COMMON_OPTIONS);

        flag = response.hasFailures();
        if (flag){
            BulkItemResponse[] items = response.getItems();
            List<String> ids = Arrays.stream(items).map(BulkItemResponse::getId).collect(Collectors.toList());
            log.error("商品批量上架错误！{},原因:{}",ids,response);
        }

        return flag;
    }
}
